package org.linlinjava.litemall.web.service;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.google.common.annotations.VisibleForTesting;
import org.linlinjava.litemall.core.exception.BusinessRuntimeException;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.ResponseUtil.Response;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.dto.AdminShopSpecialDateDTO;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.web.dto.WebGoodsTaxDTO;
import org.linlinjava.litemall.web.vo.*;
import org.linlinjava.litemall.web.vo.goods.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import static org.linlinjava.litemall.core.exception.util.ServiceExceptionUtil.exception;
import static org.linlinjava.litemall.web.ErrorCodeConstants.LUMIERE_PACKAGE_IS_NULL;
import static org.linlinjava.litemall.web.util.WebResponseCode.*;
import static org.linlinjava.litemall.web.util.WebResponseCode.SHOP_CLOSED;

/**
 * 订单服务
 */
@Service
public class WebGoodsService {

    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallGoodsSpecificationService specService;
    @Autowired
    private LitemallGoodsAccessoryService accessoryService;
    @Autowired
    private LitemallGoodsSpecificationMerchandiseService specMerchandiseService;
    @Autowired
    private LitemallGoodsProductService productService;
    @Autowired
    private LitemallShopRegionService shopRegionService;

    @Autowired
    private LitemallRegionService litemallRegionService;
    @Autowired
    private LitemallGoodsPropertyService goodsPropertyService;

    @Autowired
    private LitemallShopService litemallShopService;
    @Autowired
    private LitemallGoodsAccessoryGroupService goodsAccessoryGroupService;
    @Autowired
    private LitemallMerchandiseService litemallMerchandiseService;

    @Autowired
    private LitemallGoodsAccessoryService litemallGoodsAccessoryService;

    @Autowired
    private LitemallGoodsRegionService litemallGoodsRegionService;

    @Autowired
    private LitemallTaxService litemallTaxService;

    @Autowired
    private LumiereGoodsFormulaCorrelationService lumiereGoodsFormulaCorrelationService;

    @Autowired
    private LumiereFormulaService lumiereFormulaService;

    @Autowired
    private LumiereFormulaMaterialService lumiereFormulaMaterialService;

    @Autowired
    private LumiereFormulaSpecificationsService lumiereFormulaSpecificationsService;

    @Autowired
    private LumiereFormulaSpecificationsDataProportioningService lumiereFormulaSpecificationsDataProportioningService;

    @Autowired
    private LumierePackageService lumierePackageService;

    @Autowired
    private LumierePackageCategoryService lumierePackageCategoryService;

    @Autowired
    private LumierePackageCategoryGoodsService lumierePackageCategoryGoodsService;


    /**
     * 查询商品详情
     *
     * @param shopId 门店id
     * @param id     商品id
     * @return
     */
    public Response<GoodsDetailResponseVO> detail(Integer shopId, Integer id) {
        LitemallGoods goods = goodsService.findById(id);
        if (null == goods) {
            return ResponseUtil.fail(GOODS_UNKNOWN, "商品不存在");
        }

        GoodsDetailResponseVO response = new GoodsDetailResponseVO();
        BeanUtils.copyProperties(goods, response);

        //查询规格列表
        List<GoodsDetailSpecVO> specifications = new ArrayList<>();
        List<LitemallGoodsSpecification> specList = specService.queryByGid(id);
        if (!CollectionUtils.isEmpty(specList)) {
            for (LitemallGoodsSpecification litemallGoodsSpecification : specList) {
                GoodsDetailSpecVO goodsDetailSpecVo = new GoodsDetailSpecVO();
                BeanUtils.copyProperties(litemallGoodsSpecification, goodsDetailSpecVo);

                //查询规格原料
                Integer specId = litemallGoodsSpecification.getId();
                List<LitemallGoodsSpecificationMerchandise> specMerList = specMerchandiseService.queryBySpecid(specId);
                List<GoodsDetailSpecMerVO> specMers = new ArrayList<>();
                for (LitemallGoodsSpecificationMerchandise litemallGoodsSpecificationMerchandise : specMerList) {
                    GoodsDetailSpecMerVO goodsDetailSpecMerVo = new GoodsDetailSpecMerVO();
                    BeanUtils.copyProperties(litemallGoodsSpecificationMerchandise, goodsDetailSpecMerVo);
                    specMers.add(goodsDetailSpecMerVo);
                }
                goodsDetailSpecVo.setSpecMers(specMers);
                specifications.add(goodsDetailSpecVo);
            }
        }
        response.setSpecifications(specifications);

        //查询属性列表
        List<GoodsDetailPropVO> props = new ArrayList<>();
        List<LitemallGoodsProperty> propList = goodsPropertyService.queryByGoodsId(id);
        if (!CollectionUtils.isEmpty(propList)) {
            for (LitemallGoodsProperty litemallGoodsProperty : propList) {
                GoodsDetailPropVO goodsDetailPropVo = new GoodsDetailPropVO();
                BeanUtils.copyProperties(litemallGoodsProperty, goodsDetailPropVo);


                props.add(goodsDetailPropVo);
            }
        }
        response.setProps(props);

        List<GoodsDetailAccessoryVO> accessorys = new ArrayList<>();
        List<LitemallGoodsAccessory> goodsAccessoryList = accessoryService.queryByGoodsId(id);
        if (!CollectionUtils.isEmpty(specList)) {
            for (LitemallGoodsAccessory litemallGoodsAccessory : goodsAccessoryList) {
                GoodsDetailAccessoryVO goodsDetailAccessoryVo = new GoodsDetailAccessoryVO();
                BeanUtils.copyProperties(litemallGoodsAccessory, goodsDetailAccessoryVo);
                accessorys.add(goodsDetailAccessoryVo);
            }
        }
        response.setAccessorys(accessorys);
        return ResponseUtil.ok(response);
    }


    /**
     * 有效商店
     *
     * @param shopId 商店id
     * @return {@link Response}<{@link Object}>
     */
    private boolean validShop(Integer shopId) {
        if (shopId == null) {
            return false;
        }
        LitemallShop shop = litemallShopService.findById(shopId);
        // 假设门店的营业时间已经存在于 shop.getWeeksTime() 集合中
        List<LocalTime[]> weeksTime = shop.getWeeksTime();
        if (weeksTime == null) {
            return false;
        }
        // 获取当前日期和时间
        LocalDate currentDate = LocalDate.now();
        LocalTime currentTime = LocalTime.now();
        if(StrUtil.isNotEmpty(shop.getTimezone())){
            // 设置选择的时区
            ZoneId zoneId = ZoneId.of(shop.getTimezone());
            // 获取当前日期
            currentDate = LocalDate.now(zoneId);
            // 获取当前时间
            currentTime = LocalTime.now(zoneId);
        }
        // 获取当前是星期几
        DayOfWeek currentDayOfWeek = currentDate.getDayOfWeek();

        // 获取对应的门店营业时间
        LocalTime[] businessHours = weeksTime.get(currentDayOfWeek.getValue() - 1);

        // 判断当前时间是否处于门店的开业时间范围内
        boolean isOpen = currentTime.isAfter(businessHours[0]) && currentTime.isBefore(businessHours[1]);
        List<AdminShopSpecialDateDTO> specialDateList = shop.getSpecial()==null?CollUtil.newArrayList():shop.getSpecial();
        LocalDate today = LocalDate.now();
        // 遍历集合中的每个AdminShopSpecialDateDTO对象
        for (AdminShopSpecialDateDTO dto : specialDateList) {
            LocalDate specialDate = dto.getSpecialDate();
            LocalTime[] specialTime = dto.getSpecialTime();

            // 在这里进行特定逻辑处理，判断门店是否营业
            // 判断specialDate是否是今天
            if (!specialDate.isEqual(today)) {
                continue;
            }
            // 判断当前时间是否在营业时间范围内
            isOpen = currentTime.isAfter(specialTime[0]) && currentTime.isBefore(specialTime[1]);
        }
        return isOpen;
    }


    public Response<PackageDetailRespVO> packageDetail(Integer id, Integer shopId) {
        //判断门店状态
        if (!validShop(shopId)) {
            return ResponseUtil.fail(SHOP_CLOSED, "门店已歇业");
        }

        PackageDetailRespVO packageDetail = new PackageDetailRespVO();
        //套餐
        LumierePackage lumierePackage = validationPackage(id);
        packageDetail.setLumierePackage(lumierePackage);

        List<PackageCategoryVO> packageCategory = new ArrayList<>();

        //类目
        List<LumierePackageCategory> categoryList = lumierePackageCategoryService.list(Wrappers.lambdaQuery(LumierePackageCategory.class).eq(LumierePackageCategory::getPackageId, id));
        //所有类目商品
        List<LumierePackageCategoryGoods> categoryGoodAll = lumierePackageCategoryGoodsService.list(Wrappers.lambdaQuery(LumierePackageCategoryGoods.class).eq(LumierePackageCategoryGoods::getPackageId, id));
        for (LumierePackageCategory lumierePackageCategory : categoryList) {
            List<LumierePackageCategoryGoods> categoryGoods = categoryGoodAll.stream().filter(packageCategoryGoods -> packageCategoryGoods.getPackageCategoryId() == lumierePackageCategory.getId()).collect(Collectors.toList());

            //类目 类目信息+类目下所有商品
            List<PackageCategoryGoodsVO> categoryGoodsVO = new ArrayList<>();

            for (LumierePackageCategoryGoods categoryGood : categoryGoods) {
                //商品详情
                PackageCategoryGoodsVO packageCategoryGoods = new PackageCategoryGoodsVO();

                //套餐类目下商品 配置信息
                packageCategoryGoods.setCategoryGoods(categoryGood);

                //商品信息
                LitemallGoods goods = goodsService.findById(categoryGood.getGoodsId());
                packageCategoryGoods.setGoods(goods);
                //商品属性
                //List<LitemallGoodsProperty> goodsProperties = goodsPropertyService.queryByGoodsId(goods.getId());
                //packageCategoryGoods.setGoodsProperties(goodsProperties);

                //查询属性列表
                List<GoodsPropertyVO> propertyVos = goodsPropertyService.queryByGoodsId(goods.getId()).stream()
                        .map(litemallGoodsProperty -> {
                            GoodsPropertyVO propertyVo = new GoodsPropertyVO();
                            propertyVo.setId(litemallGoodsProperty.getId());
                            propertyVo.setName(litemallGoodsProperty.getName());

                            // 将字符串数组转换为 List<GoodsDetailPropertyVO>
                            List<GoodsDetailPropertyVO> vos = Arrays.stream(litemallGoodsProperty.getValues())
                                    .map(value -> {
                                        GoodsDetailPropertyVO v = new GoodsDetailPropertyVO();
                                        v.setName(value);
                                        v.setIsSelected(value.equals(litemallGoodsProperty.getIsDefault()));  // 选择第一个值
                                        return v;
                                    })
                                    .collect(Collectors.toList());

                            propertyVo.setVos(vos);
                            return propertyVo;
                        })
                        .collect(Collectors.toList());

                packageCategoryGoods.setGoodsProperties(propertyVos);


                //查看选择配方
                LumiereGoodsFormulaCorrelation goodsFormulaCorrelation = lumiereGoodsFormulaCorrelationService.getOne(Wrappers.lambdaQuery(LumiereGoodsFormulaCorrelation.class)
                        .eq(LumiereGoodsFormulaCorrelation::getGoodsId, categoryGood.getGoodsId()));

                //配方详情
                List<PackageCategoryGoodsVO.GoodsFormulaVO> goodsFormulas = new ArrayList<>();
                //配方规格
                List<LumiereFormulaSpecifications> formulaSpecifications = lumiereFormulaSpecificationsService.list(Wrappers.lambdaQuery(LumiereFormulaSpecifications.class).eq(LumiereFormulaSpecifications::getFormulaId, goodsFormulaCorrelation.getFormulaId()));


                for (LumiereFormulaSpecifications formulaSpecification : formulaSpecifications) {
                    //配方  规格[配方原料+配方规格数据配比]
                    PackageCategoryGoodsVO.GoodsFormulaVO goodsFormula =  new PackageCategoryGoodsVO.GoodsFormulaVO();

                    //配方规格数据配比
                    List<LumiereFormulaSpecificationsDataProportioning> formulaSpecificationsDataProportionings = lumiereFormulaSpecificationsDataProportioningService.list(Wrappers.lambdaQuery(LumiereFormulaSpecificationsDataProportioning.class)
                            .eq(LumiereFormulaSpecificationsDataProportioning::getFormulaSpecificationsId, formulaSpecification.getId())
                            .eq(LumiereFormulaSpecificationsDataProportioning::getIsDisplay,1));
                    //配方规格数据配比 转换成 配方原料+配方规格数据配比 ，此刻配方原料数据为空
                    List<FormulaSpecificationsDataProportioningAndMaterialVO> formulaSpecificationsDataProportioningAndMaterialVOList = formulaSpecificationsDataProportionings.stream()
                            .map(formulaSpecificationsDataProportioning->{
                                FormulaSpecificationsDataProportioningAndMaterialVO formulaSpecificationsDataProportioningAndMaterial = new FormulaSpecificationsDataProportioningAndMaterialVO();
                                BeanUtils.copyProperties(formulaSpecificationsDataProportioning,formulaSpecificationsDataProportioningAndMaterial);
                                formulaSpecificationsDataProportioningAndMaterial.setFormulaSpecificationsDataProportioningId(formulaSpecificationsDataProportioning.getId());
                                return formulaSpecificationsDataProportioningAndMaterial;
                            })
                            .collect(Collectors.toList());
                    //配方原料+配方规格数据配比 ，填充配方原料数据为空
                    formulaSpecificationsDataProportioningAndMaterialVOList.forEach(formulaSpecificationsDataProportioningAndMaterialVO->{
                        LumiereFormulaMaterial lumiereFormulaMaterial = lumiereFormulaMaterialService.getById(formulaSpecificationsDataProportioningAndMaterialVO.getFormulaMaterialId());
                        formulaSpecificationsDataProportioningAndMaterialVO.setMaterialName(lumiereFormulaMaterial.getMaterialName());
                        formulaSpecificationsDataProportioningAndMaterialVO.setMaterialImg(lumiereFormulaMaterial.getMaterialImg());
                        formulaSpecificationsDataProportioningAndMaterialVO.setMaterialClassificationName(lumiereFormulaMaterial.getMaterialClassificationName());
                        formulaSpecificationsDataProportioningAndMaterialVO.setMaterialId(lumiereFormulaMaterial.getMaterialId());
                    });

                    //分主料
                    List<FormulaSpecificationsDataProportioningAndMaterialVO> filterMaterialTypeMaster = formulaSpecificationsDataProportioningAndMaterialVOList.stream().filter(item -> item.getMaterialType() == 0).collect(Collectors.toList());
                    Map<Integer, List<FormulaSpecificationsDataProportioningAndMaterialVO>> integerListMapMaster = CollStreamUtil.groupByKey(filterMaterialTypeMaster, FormulaSpecificationsDataProportioningAndMaterialVO::getGroupName);
                    goodsFormula.setFormulaSpecificationsDataProportioningsMaster(integerListMapMaster.values());

                    //分辅料
                    List<FormulaSpecificationsDataProportioningAndMaterialVO> filterMaterialTypeSlave = formulaSpecificationsDataProportioningAndMaterialVOList.stream().filter(item->item.getMaterialType()==1).collect(Collectors.toList());
                    Map<Integer, List<FormulaSpecificationsDataProportioningAndMaterialVO>> integerListMapSlave = CollStreamUtil.groupByKey(filterMaterialTypeSlave, FormulaSpecificationsDataProportioningAndMaterialVO::getGroupName);
                    goodsFormula.setFormulaSpecificationsDataProportioningsSlave(integerListMapSlave.values());

                    //配方规格+[配方原料+配方规格数据配比]
                    goodsFormula.setFormulaSpecifications(formulaSpecification);

                    goodsFormulas.add(goodsFormula);
                }
                packageCategoryGoods.setGoodsFormulas(goodsFormulas);
                categoryGoodsVO.add(packageCategoryGoods);
            }
            packageCategory.add(new PackageCategoryVO(lumierePackageCategory,categoryGoodsVO));
        }
        //税收配置
        LitemallGoodsRegion goodRegion = litemallGoodsRegionService.findByPackageIdAndCityId(id, getShopRegionId(shopId));
        List<LitemallTax> taxList = goodRegion == null || goodRegion.getTaxTypes().length == 0 ?
                CollUtil.newArrayList() : litemallTaxService.selectEnabledByIds(CollectionUtils.arrayToList(goodRegion.getTaxTypes()));
        packageDetail.setTaxList(taxList);
        packageDetail.setPackageCategorys(packageCategory);
        return ResponseUtil.ok(packageDetail);
    }


    @VisibleForTesting
    private LumierePackage validationPackage(Integer packageId){
        //套餐
        LumierePackage lumierePackage = lumierePackageService.getById(packageId);
        if(lumierePackage==null){
            throw exception(LUMIERE_PACKAGE_IS_NULL);
        }
        return lumierePackage;
    }


    /**
     * 新细节
     * 查询商品详情
     *
     * @param id 商品id
     * @return {@link Response}<{@link LlitemallGoodsDetailVO}>
     */
    public Response<LlitemallGoodsDetailVO> newDetail(Integer id, Integer shopId) {
        LitemallGoods goods = goodsService.findById(id);
        if (null == goods) {
            return ResponseUtil.fail(GOODS_UNKNOWN, "商品不存在");
        }
        //判断门店状态
        if (!validShop(shopId)) {
            return ResponseUtil.fail(SHOP_CLOSED, "门店已歇业");
        }
        LlitemallGoodsDetailVO vo = new LlitemallGoodsDetailVO();
        BeanUtils.copyProperties(goods, vo);

 		//查询属性列表
        List<GoodsPropertyVO> propertyVos = new ArrayList<>();
        List<LitemallGoodsProperty> propList = goodsPropertyService.queryByGoodsId(id);
        if (!CollectionUtils.isEmpty(propList)) {
            for (LitemallGoodsProperty litemallGoodsProperty : propList) {
                GoodsPropertyVO propertyVo = new GoodsPropertyVO();
                propertyVo.setId(litemallGoodsProperty.getId());
                propertyVo.setName(litemallGoodsProperty.getName());

                List<GoodsDetailPropertyVO> vos = new ArrayList();
                String[] values = litemallGoodsProperty.getValues();
                for (int i = 0; i < values.length; i++) {
                    GoodsDetailPropertyVO v = new GoodsDetailPropertyVO();
                    v.setName(values[i]);
                    v.setIsSelected(litemallGoodsProperty.getIsDefault().equals(values[i]));
                    vos.add(v);
                }
                propertyVo.setVos(vos);
                propertyVos.add(propertyVo);
            }
        }
        vo.setPropertyVos(propertyVos);


        //查看选择配方
        LumiereGoodsFormulaCorrelation goodsFormulaCorrelation = lumiereGoodsFormulaCorrelationService.getOne(Wrappers.lambdaQuery(LumiereGoodsFormulaCorrelation.class)
                .eq(LumiereGoodsFormulaCorrelation::getGoodsId, goods.getId()));
        //vo.setIsFormula(goodsFormulaCorrelation != null);

        //配方
        vo.setFormula(lumiereFormulaService.getById(goodsFormulaCorrelation.getFormulaId()));

        //配方详情
        List<FormulaSpecificationsVO> goodsFormulas = new ArrayList<>();
        //配方规格
        List<LumiereFormulaSpecifications> formulaSpecifications = lumiereFormulaSpecificationsService.list(Wrappers.lambdaQuery(LumiereFormulaSpecifications.class).eq(LumiereFormulaSpecifications::getFormulaId, goodsFormulaCorrelation.getFormulaId()));

        for (LumiereFormulaSpecifications formulaSpecification : formulaSpecifications) {
            //配方  规格[配方原料+配方规格数据配比]
            FormulaSpecificationsVO goodsFormula =  new FormulaSpecificationsVO();

            //配方规格数据配比
            /*List<LumiereFormulaSpecificationsDataProportioning> formulaSpecificationsDataProportionings = lumiereFormulaSpecificationsDataProportioningService.list(Wrappers.lambdaQuery(LumiereFormulaSpecificationsDataProportioning.class)
                    .eq(LumiereFormulaSpecificationsDataProportioning::getFormulaSpecificationsId, formulaSpecification.getId())
                    );*/

            List<LumiereFormulaSpecificationsDataProportioning> formulaSpecificationsDataProportionings = lumiereFormulaSpecificationsDataProportioningService.selectJoinList(LumiereFormulaSpecificationsDataProportioning.class,new MPJLambdaWrapper<LumiereFormulaSpecificationsDataProportioning>()
                    .selectAll(LumiereFormulaSpecificationsDataProportioning.class)
                    .leftJoin(LumiereFormulaMaterial.class,LumiereFormulaMaterial::getId,LumiereFormulaSpecificationsDataProportioning::getFormulaMaterialId)
                    .eq(LumiereFormulaSpecificationsDataProportioning::getFormulaSpecificationsId, formulaSpecification.getId())
                    .eq(LumiereFormulaSpecificationsDataProportioning::getIsDisplay,1)
                    .orderByDesc(LumiereFormulaSpecificationsDataProportioning::getGroupName)
            );

            //配方规格数据配比 转换成 配方原料+配方规格数据配比 ，此刻配方原料数据为空
            List<FormulaSpecificationsDataProportioningAndMaterialVO> formulaSpecificationsDataProportioningAndMaterialVOList = CollStreamUtil.toList(formulaSpecificationsDataProportionings,formulaSpecificationsDataProportioning->{
                FormulaSpecificationsDataProportioningAndMaterialVO formulaSpecificationsDataProportioningAndMaterial = new FormulaSpecificationsDataProportioningAndMaterialVO();
                BeanUtils.copyProperties(formulaSpecificationsDataProportioning,formulaSpecificationsDataProportioningAndMaterial);
                formulaSpecificationsDataProportioningAndMaterial.setFormulaSpecificationsDataProportioningId(formulaSpecificationsDataProportioning.getId());
                return formulaSpecificationsDataProportioningAndMaterial;
            });
            //配方原料+配方规格数据配比 ，填充配方原料数据为空
            formulaSpecificationsDataProportioningAndMaterialVOList.forEach(formulaSpecificationsDataProportioningAndMaterialVO->{
                LumiereFormulaMaterial lumiereFormulaMaterial = lumiereFormulaMaterialService.getById(formulaSpecificationsDataProportioningAndMaterialVO.getFormulaMaterialId());
                formulaSpecificationsDataProportioningAndMaterialVO.setMaterialName(lumiereFormulaMaterial.getMaterialName());
                formulaSpecificationsDataProportioningAndMaterialVO.setMaterialImg(lumiereFormulaMaterial.getMaterialImg());
                formulaSpecificationsDataProportioningAndMaterialVO.setMaterialId(lumiereFormulaMaterial.getMaterialId());
                formulaSpecificationsDataProportioningAndMaterialVO.setMaterialClassificationName(lumiereFormulaMaterial.getMaterialClassificationName());
            });

            //分主料
            List<FormulaSpecificationsDataProportioningAndMaterialVO> filterMaterialTypeMaster = formulaSpecificationsDataProportioningAndMaterialVOList.stream().filter(item -> item.getMaterialType() == 0).collect(Collectors.toList());
            Map<Integer, List<FormulaSpecificationsDataProportioningAndMaterialVO>> integerListMapMaster = CollStreamUtil.groupByKey(filterMaterialTypeMaster, FormulaSpecificationsDataProportioningAndMaterialVO::getGroupName);
            goodsFormula.setFormulaSpecificationsDataProportioningsMaster(integerListMapMaster.values());

            //分辅料
            List<FormulaSpecificationsDataProportioningAndMaterialVO> filterMaterialTypeSlave = formulaSpecificationsDataProportioningAndMaterialVOList.stream().filter(item->item.getMaterialType()==1).collect(Collectors.toList());
            Map<Integer, List<FormulaSpecificationsDataProportioningAndMaterialVO>> integerListMapSlave = CollStreamUtil.groupByKey(filterMaterialTypeSlave, FormulaSpecificationsDataProportioningAndMaterialVO::getGroupName);
            goodsFormula.setFormulaSpecificationsDataProportioningsSlave(integerListMapSlave.values());

            //配方规格+[配方原料+配方规格数据配比]
            goodsFormula.setFormulaSpecifications(formulaSpecification);
            goodsFormulas.add(goodsFormula);
        }
        vo.setGoodsFormulas(goodsFormulas);

        //商品税费
        Integer shopRegionId = getShopRegionId(shopId);
        LitemallGoodsRegion goodRegion = litemallGoodsRegionService.findByGidAndCityId(goods.getId(), shopRegionId);
        if (null == goodRegion) {
            throw new BusinessRuntimeException(ORDER_GOODS_SHOP_INVALID_OPERATION, "该店铺无操作商品的权限");
        }
        vo.setGoodsTaxs(CollUtil.newArrayList());
        if(0<goodRegion.getTaxTypes().length){
            List<WebGoodsTaxDTO> goodsTaxs = litemallTaxService.selectEnabledByIds(Arrays.asList(goodRegion.getTaxTypes())).stream().map(litemallTax -> {
                        if (null == litemallTax) {
                            throw new BusinessRuntimeException(TAX_REGION_NOT_SET, "该区域未配置税收类型");
                        } else if (litemallTax.getDeleted() || (!litemallTax.getEnable())) {
                            return null;
                        }
                        return WebGoodsTaxDTO.builder().code(litemallTax.getCode()).value(litemallTax.getValue()).build();
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            vo.setGoodsTaxs(goodsTaxs);
        }
        return ResponseUtil.ok(vo);
    }

    /**
     * 获取店铺的地区id
     *
     * @param shopId
     */
    private Integer getShopRegionId(Integer shopId) {
        List<LitemallShopRegion> litemallShopRegions = shopRegionService.queryByShopId(shopId);
        if (!CollectionUtils.isEmpty(litemallShopRegions)) {
            for (LitemallShopRegion litemallShopRegion : litemallShopRegions) {
                LitemallRegion litemallRegion = litemallRegionService.findById(litemallShopRegion.getRegionId());
                if (Constants.REGION_TYPE_CITY == litemallRegion.getType()) {
                    return litemallShopRegion.getRegionId();
                }
            }
        }
        return null;
    }


    /**
     * 根据条件搜素跟店铺同一地区的总部商品和店铺商品）
     *
     * @return
     */
    public List<GoodsVO> list(Integer shopId, Integer catId, Integer brandId, String keywords, Boolean isHot, Boolean isNew, Integer page, Integer limit, String sort, String order) {
        //查询列表数据
        GoodsQueryVo query = new GoodsQueryVo();
        query.setShopId(shopId);
        query.setCatId(catId);
        query.setBrandId(brandId);
        query.setIsHot(isHot);
        query.setIsNew(isNew);
        query.setIsOnSale(true);
        query.setKeywords(keywords);

        //查询店铺的区域地址
        Integer countryRegionId = null;
        Integer provinceRegionId = null;
        Integer cityRegionId = null;
        List<LitemallShopRegion> litemallShopRegions = shopRegionService.queryByShopId(shopId);
        if (!CollectionUtils.isEmpty(litemallShopRegions)) {
            for (LitemallShopRegion litemallShopRegion : litemallShopRegions) {
                LitemallRegion litemallRegion = litemallRegionService.findById(litemallShopRegion.getRegionId());
                if (Constants.REGION_TYPE_COUNTRY == litemallRegion.getType()) {
                    countryRegionId = litemallShopRegion.getRegionId();
                } else if (Constants.REGION_TYPE_PROVINCE == litemallRegion.getType()) {
                    provinceRegionId = litemallShopRegion.getRegionId();
                } else if (Constants.REGION_TYPE_CITY == litemallRegion.getType()) {
                    cityRegionId = litemallShopRegion.getRegionId();
                }
            }
        }
        query.setCountryRegionId(countryRegionId);
        query.setProvinceRegionId(provinceRegionId);
        query.setCityRegionId(cityRegionId);
        query.setIsOnSale(true);

        List<LitemallGoods> goodsList = goodsService.queryShopGoodsByCondition(query, page, limit, sort, order);
        List<GoodsVO> goodsVos = goodsList.stream().map(goods -> {
            List<LitemallGoodsProduct> litemallGoodsProducts = productService.queryByGid(goods.getId());
            GoodsVO vo = new GoodsVO();
            vo.setBrief(goods.getBrief());
            vo.setIsHot(goods.getIsHot());
            vo.setId(goods.getId());
            vo.setName(goods.getName());
            vo.setIsNew(goods.getIsNew());
            vo.setPicUri(goods.getPicUrl());

            if (litemallGoodsProducts.size() > 0) {
                vo.setRetailPrice(litemallGoodsProducts.get(0).getSellPrice());
            }
            return vo;
        }).collect(Collectors.toList());

        return goodsVos;
    }

    public List<LitemallGoodsDetailAccessoryVO> beanReverse(Integer groupId, List<Integer> merIds, Integer id) {
        List<LitemallGoodsAccessory> accessories = accessoryService.queryByGroupId(groupId);
        List<LitemallGoodsDetailAccessoryVO> vos = accessories.stream().map(accessory -> {
            boolean flag = false;
            LitemallMerchandise merchandise = litemallMerchandiseService.findById(accessory.getMerchandiseId());
            LitemallGoodsDetailAccessoryVO vo = new LitemallGoodsDetailAccessoryVO();

            vo.setId(accessory.getId());
            vo.setName(accessory.getGroupName());
            vo.setCostType(accessory.getCostType());
            vo.setUnit(merchandise.getBasicUnit());
            vo.setMerchandiseId(merchandise.getId());
            vo.setSelectedNum(0);
            vo.setPrice(accessory.getPrice());
            //查看在规格中是否有这个辅料
            for (int i = 0; i < merIds.size(); i++) {
                if (merchandise.getId().equals(merIds.get(i))) {
                    flag = true;
                    break;
                }
            }

            vo.setIsDefaultValue(flag);

            vo.setIsSelected(flag);
            vo.setNumber(accessory.getNumber());
            vo.setMuchContent(accessory.getMuchContent());
            vo.setFewContent(accessory.getFewContent());
            return vo;
        }).collect(Collectors.toList());
        return vos;
    }



}
